Closed-loop sytem for5 weaning from mechanical ventilation